package com.nanjing.east.cloud.wechatpay;

import com.nanjing.east.cloud.PayOrderDTO;
import com.nanjing.east.cloud.domain.PayHardware;
import com.nanjing.east.cloud.domain.PayOrder;
import com.nanjing.east.cloud.service.HardwareService;
import com.nanjing.east.cloud.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class WechatPayClient {

    @Autowired
    private OrderService orderService;
    @Autowired
    private HardwareService hardwareService;

    public String preCreateOrder(PayOrderDTO payOrderDTO) throws Exception {
        MyConfig config = new MyConfig();
        WXPay wxpay = new WXPay(config);

        Map<String, String> data = new HashMap<String, String>();
        data.put("body", "超市寄存柜使用费");
        data.put("out_trade_no", payOrderDTO.getPayOrderNo());
        data.put("device_info", "");
        data.put("fee_type", "CNY");
        data.put("total_fee", payOrderDTO.getPayAmount());
        data.put("spbill_create_ip", "123.12.12.123");
        data.put("notify_url", "http://www.example.com/wxpay/notify");
        data.put("trade_type", "NATIVE");  // 此处指定为扫码支付
        data.put("product_id", "12");

        Map<String, String> unifiedOrder = wxpay.unifiedOrder(data);
        String qrCode = unifiedOrder.get("code_url");
        PayOrder payOrder = PayOrder.builder()
                .storeId(payOrderDTO.getStoreId())
                .payOrderNo(payOrderDTO.getPayOrderNo())
                .payAmount(payOrderDTO.getPayAmount())
                .payTradeType("NATIVE")
                .payChannelId(1)
                .payResult(0)
                .qrCode(qrCode)
                .build();
        orderService.createOrder(payOrder);
        PayHardware payHardware = PayHardware.builder()
                .payOrderNo(payOrderDTO.getPayOrderNo())
                .storeId(payOrderDTO.getStoreId())
                .cabinetId(payOrderDTO.getCabinetId())
                .lockId(payOrderDTO.getLockId())
                .lockStatus("0")
                .build();
        hardwareService.createPayHardware(payHardware);
        return qrCode;
    }

    public void refreshOrder(String payOrderNo) {
        try {
            Map<String, String> data = new HashMap<String, String>();
            data.put("out_trade_no", payOrderNo);
            MyConfig config = new MyConfig();
            WXPay wxpay = new WXPay(config);
            Map<String, String> orderQuery = wxpay.orderQuery(data);

            //Map<String, String> orderQuery = mock_wechat_query(data);

            String returnCode = orderQuery.get("return_code");
            String tradeState = orderQuery.get("trade_state");
            String tradeStateDesc = orderQuery.get("trade_state_desc");
            String transactionId = orderQuery.get("transaction_id");
            if (StringUtils.equals("SUCCESS", returnCode)) {
                if (StringUtils.equals("SUCCESS", tradeState)) {
                    PayOrder payOrder = PayOrder.builder()
                            .payResult(2)
                            .payResponseMsg(tradeStateDesc)
                            .outerOrderNo(transactionId)
                            .build();
                    PayOrder order = orderService.queryOrderByNo(payOrderNo);
                    orderService.updateOrder(order, payOrder);
                } else if (StringUtils.equals("NOTPAY", tradeState)
                        || StringUtils.equals("USERPAYING", tradeState)) {
                    PayOrder payOrder = PayOrder.builder()
                            .payResult(0)
                            .payResponseMsg(tradeStateDesc)
                            .outerOrderNo(transactionId)
                            .build();
                    PayOrder order = orderService.queryOrderByNo(payOrderNo);
                    orderService.updateOrder(order, payOrder);
                } else {
                    PayOrder payOrder = PayOrder.builder()
                            .payResult(3)
                            .payResponseMsg(tradeStateDesc)
                            .outerOrderNo(transactionId)
                            .build();
                    PayOrder order = orderService.queryOrderByNo(payOrderNo);
                    orderService.updateOrder(order, payOrder);
                }
            } else {
                PayOrder payOrder = PayOrder.builder()
                        .payResult(3)
                        .payResponseMsg(tradeStateDesc)
                        .outerOrderNo(transactionId)
                        .build();
                PayOrder order = orderService.queryOrderByNo(payOrderNo);
                orderService.updateOrder(order, payOrder);
            }
        } catch (Exception e) {
            log.error("WechatPayClient.refreshOrder error :{}", e);
        }

    }

    private Map<String, String> mock_wechat_query(Map<String, String> data) {
        Map<String ,String > map = new HashMap<>();
        map.put("return_code","0");
        return map;
    }
}
